const express = require("express")
const log = require("../middleware/log")
const loginApp = express()
const Notice = require("../model/Notice")
const { resErr, resSuccess, resExpire } = require("../public/tip.js")

// 用户删除
loginApp.post("/delete", async (req, res) => {
  const { id } = req.body
  const user = await User.deleteUser(id)
  console.log(user)
  if (user) {
    res.send(resSuccess)
  } else {
    res.send(resErr)
  }
})

// 保存/编辑
loginApp.post("/change", async (req, res) => {
  let { id, title, content } = req.body
  if (id) {
    //更新
    const user_res = await Notice.updateNotice(id, title, content)
    res.send(resSuccess)
  } else {
    //新增
    const user_res = await Notice.saveNotice(title, content)
    res.send(resSuccess)
  }
})

//admin查询公告
loginApp.get("/adminlist", async (req, res) => {
  let { keyword, pageNum, pageSize } = req.query
  pageSize = Number(pageSize)
  const currentPage = (Number(pageNum) - 1) * pageSize
  try {
    const users = await Notice.findAll(keyword, currentPage, pageSize)
    const users_count = await Notice.count(keyword)
    res.send({ ...resSuccess, msg: "查询成功", data: users, total: users_count })
  } catch {
    res.send({ ...resErr })
  }
})

//查询所有公告
loginApp.get("/list", async (req, res) => {
  let { token } = req.headers
  let { keyword, pageNum, pageSize, key } = req.query
  pageSize = Number(pageSize)
  const currentPage = (Number(pageNum) - 1) * pageSize
  let user = await Notice.verifyToken(token)
  console.log(user)
  if (user.length > 0 || key === "admin") {
    try {
      const users = await Notice.findAll(keyword, currentPage, pageSize)
      const users_count = await Notice.count(keyword)
      res.send({ ...resSuccess, msg: "查询成功", data: users, total: users_count })
    } catch {
      res.send({ ...resErr })
    }
  } else {
    res.send(resExpire)
  }
})

module.exports = loginApp
